package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.channel.IChannelClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.HotArticleSrevice;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class HotArticleSreviceImpl implements HotArticleSrevice {

    //article
    private final ApArticleMapper articleMapper;

    //channel
    private final IChannelClient channelClient;

    //redis
    private  final CacheService cacheService;
    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {

        //1.查询前五天的文章数据
        Date dateParam = DateTime.now().minusDays(5).toDate();
        List<ApArticle> apArticleList = articleMapper.findArticleListByLast5days(dateParam);

        //2.计算文章的分值
        List<HotArticleVo> hotArticleVos = computeHotArticleScore(apArticleList);

        //3.为每个频道缓存30条分值较高的文章
        cacheTagToRedis(hotArticleVos);
    }

    /**
     * 为每个频道缓存30条文章
     * @param hotArticleVos
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVos) {

        //频道文章缓存

        //查询所有频道
        ResponseResult result = channelClient.findAll();
        if (result.getCode().equals(200)) {

            //拿取全部频道
            String jsonString = JSON.toJSONString(result.getData());
            List<WmChannel> wmChannels = JSON.parseArray(jsonString, WmChannel.class);

            //检索出每个文章的热点频道
            if (wmChannels != null && wmChannels.size() > 0) {
                for (WmChannel wmChannel : wmChannels) {

                    //获取该频道 是热点文章的文章
                    List<HotArticleVo> collect = hotArticleVos.stream().filter(x -> x.getChannelId().equals(wmChannel.getId())).collect(Collectors.toList());

                    //为文章进行排序 取30条分值较高的文章存入reids key:频道  value: 30条分值较高的文章
                                          //排序    //按分值进行排序                            //倒叙
                    List<HotArticleVo> sortHotArticle = collect .stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());

                    if(sortHotArticle.size() > 30){
                        //截取30条数据
                        hotArticleVos = sortHotArticle.subList(0, 30);
                    }

                    //将这30条数据混存到redis中            热点文章缓存
                    cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+wmChannel.getId(),JSON.toJSONString(hotArticleVos));
                }
            }


            //推荐文章缓存

            //为文章进行排序 取30条分值较高的文章存入reids key:频道  value: 30条分值较高的文章
            //排序    //按分值进行排序                            //倒叙
            List<HotArticleVo> sortHotArticle = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());

            if(sortHotArticle.size() > 30){
                //截取30条数据
                hotArticleVos = sortHotArticle.subList(0, 30);
            }

            //将这30条数据混存到redis中            推荐文章缓存
            cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG,JSON.toJSONString(hotArticleVos));

        }


    }

    /**
     * 计算热点文章
     *
     * @param apArticleList
     *
     * @return
     */
    private List<HotArticleVo> computeHotArticleScore(List<ApArticle> apArticleList) {

        //装热点文章
        List<HotArticleVo> hotArticleVosList = new ArrayList<>();


        if (apArticleList != null || apArticleList.size() > 0) {
            for (ApArticle apArticle : apArticleList) {

                HotArticleVo hot = new HotArticleVo();

                BeanUtils.copyProperties(apArticle, hot);

                //计算文章分值
                Integer score = computeScore(apArticle);

                //为文章设置分值
                hot.setScore(score);

                //放进热点文章
                hotArticleVosList.add(hot);

            }
        }

        return hotArticleVosList;

    }

    /**
     * 计算文章分值
     *
     * 对用户行为进行 加权来计算分值
     *
     * 阅读    1
     * 点赞    3
     * 评论    5
     * 收藏    8
     *
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {

        Integer score = 0;

        //点赞分值计算
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes()* ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }

        //评论分值计算
        if (apArticle.getComment() != null) {
            score += apArticle.getComment()* ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }

        //收藏分值计算
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection()* ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        //阅读分值计算
        if (apArticle.getViews() != null) {
            score += apArticle.getViews();
        }

        return score;
    }

}
